import React, { PureComponent, Fragment } from 'react';
import {
  Drawer,
  Col,
  Row,
  Tabs, Button, Icon,
} from 'antd';
import { connect } from 'dva';
import groupBy from 'lodash/groupBy';
import forEach from 'lodash/forEach';
import ReactDataGrid from 'react-data-grid';
import find from 'lodash/find';
import styles from './../ValveFlowMeterSite/index.less'
import gold_groud from './../../images/valve_small.png'
import gold_groud2 from './../../images/valve2_small.jpg'
import unknow from './../../images/unknow.png'

const { TabPane } = Tabs;

@connect(({ devices, loading }) => ({
  devices,
}))
class BasicList extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      group: {},
      groupNameMap: {
        'press_sensor': '压力监测站点',
        'flow_meter': '流量监测站点',
        'pipe': '现状管道',
      },
    };
  }


  componentDidMount() {
    const group = groupBy(this.props.selectFeature, 'ground_set');
    console.log('group', group);
    this.setState({
      group,
    });

  }

  componentWillUnmount() {
  }

  renderStatus = (val) => {
    let type = '';
    let color = '';
    let text = '';
    switch (val) {
      case 1:
        type = 'check-circle', color = '#004cff', text = '在线';
        break;
      case -1:
        type = 'close-circle', color = '#fe1b2e', text = '离线';
        break;
      default:
        type = 'close-circle', color = '#eb2f96', text = '异常';
        break;
    }
    return <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
  };
  renderTabPane = (group) => {
    const that = this;
    const defaultColumnProperties = {
      resizable: true,
    };
    const defaultColumnProperties2 = {
      resizable: true,
      sortable: true,
    };
    const columns = [
      {
        name: '压力传感器名称',
        width: 190,
        key: 'name',

      },
      {
        name: '安装地址',
        width: 190,
        key: 'address',
      },
      {
        name: 'IMEI',
        key: 'imei',
        width: 150,
      },

      {
        name: '在线状态',
        key: 'online_status',
        width: 100,
        formatter: (event) => {
          return this.renderStatus(event.value);
        },
      },
      {
        name: '最新上传数据时间',
        width: 200,
        key: 'upload_time',
        formatter: (event) => {
          if(!event.row.workstation_data.pressure_sensor||event.row.workstation_data.pressure_sensor.length==0){
            return  ''
          }
          return <p>{event.row.workstation_data.pressure_sensor[0].collected_at}</p>
        }
      },
      {
        name: '最新压力(m³)',
        width: 120,
        key: 'pressure',
        formatter: (event) => {
          if(!event.row.workstation_data.pressure_sensor||event.row.workstation_data.pressure_sensor.length==0){
            return  ''
          }
          return <p className={event.row.workstation_data.pressure_sensor[0].parameters.pressure_status==0?'table-success table-status':'table-error table-status' }>{
            event.row.workstation_data.pressure_sensor[0].parameters.pressure
          }</p>
        }
      },
      {
        name: '操作',
        width: 100,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            className={'btn-cyan'}
            type="primary"
            icon="eye"
            size="small"
            onClick={(e) => {
              e.stopPropagation();
              this.props.showDetail(event.row);
            }
            }
          >详情
          </Button>
        </Fragment>,
      },
    ].map(c => ({ ...defaultColumnProperties, ...c }));
    const flowMeterColumns =  [
      {
        name: '压力传感器名称',
        width: 190,
        key: 'name',

      },
      {
        name: '安装地址',
        width: 190,
        key: 'address',
      },
      {
        name: 'IMEI',
        key: 'imei',
        width: 150,
      },

      {
        name: '在线状态',
        key: 'online_status',
        width: 100,
        formatter: (event) => {
          return this.renderStatus(event.value);
        },
      },
      {
        name: '最新上传数据时间',
        width: 200,
        key: 'upload_time',
        formatter: (event) => {
          if(!event.row.workstation_data.flowmeter||event.row.workstation_data.flowmeter.length==0){
            return  ''
          }
          return <p>{event.row.workstation_data.flowmeter[0].collected_at}</p>
        }
      },
      {
        name: '最新压力(m³)',
        width: 120,
        key: 'pressure',
        formatter: (event) => {
          if(!event.row.workstation_data.flowmeter||event.row.workstation_data.flowmeter.length==0){
            return  ''
          }
          return <p className={event.row.workstation_data.pressure_sensor[0].parameters.flowmeter==0?'table-success table-status':'table-error table-status' }>{
            event.row.workstation_data.flowmeter[0].parameters.positive_cumulative_flow
          }</p>
        }
      },
      {
        name: '操作',
        width: 100,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            className={'btn-cyan'}
            type="primary"
            icon="eye"
            size="small"
            onClick={(e) => {
              e.stopPropagation();
              this.props.showDetail(event.row);
            }
            }
          >详情
          </Button>
        </Fragment>,
      },
    ].map(c => ({ ...defaultColumnProperties, ...c }));
    const pipeColumns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          return <p className={'index'}>{(event.value + 1)}</p>;
        },
      },
      {
        name: 'ID',
        width: 130,
        key: 'id',
        sortDescendingFirst: true,

      },
      {
        name: '起点埋深(m)',
        key: '起点埋深',
        width: 120,
      },
      {
        name: '终点埋深(m)',
        key: '终点埋深',
        width: 120,
      },
      {
        name: '材质',
        key: '材质',
        width: 120,
        sortDescendingFirst: true,
      },
      {
        name: '埋设方式',
        key: '埋设方式',
        width: 120,
      },
      {
        name: '线型',
        key: '线型',
        width: 120,
      },
      {
        name: '管径',
        key: '管径',
        width: 120,
        sortDescendingFirst: true,
      },
      {
        name: '长度(m)',
        key: '长度',
        width: 150,
        formatter: (event) => <Fragment>
          {event.value.toFixed(2)}
        </Fragment>,
      },
    ].map(c => ({ ...defaultColumnProperties2, ...c }));

    let result = [];
    for (let key  in group) {
      if (key === 'press_sensor') {
        result.push(
          <TabPane tab={<span>{this.state.groupNameMap[key]}({group[key].length})</span>} key={key}>
            <ReactDataGrid
              columns={columns}
              rowGetter={i => group[key][i]}
              rowsCount={group[key].length}
              minHeight={400}

            />
          </TabPane>,
        );
      } else if (key === 'flow_meter') {
        result.push(
          <TabPane tab={<span>{this.state.groupNameMap[key]}({group[key].length})</span>} key={key}>
            <ReactDataGrid
              columns={flowMeterColumns}
              rowGetter={i => group[key][i]}
              rowsCount={group[key].length}
              minHeight={400}

            />
          </TabPane>,
        );
      } else if (key === 'pipe') {
        let totalLength = 0;
        for (let i = 0; i < group[key].length; i++) {
          totalLength += Number(group[key][i]['长度']);
        }
        result.push(
          <TabPane tab={<span>{this.state.groupNameMap[key]}({group[key].length})</span>} key={key}>
            <ReactDataGrid
              columns={pipeColumns}
              rowGetter={i => {
                return { ...group[key][i], _index: i };
              }}
              rowsCount={group[key].length}
              minHeight={400}
              onGridSort={(sortColumn, sortDirection) => {
                const comparer = (a, b) => {
                  if (sortDirection === 'ASC') {
                    return a[sortColumn] > b[sortColumn] ? 1 : -1;
                  } else if (sortDirection === 'DESC') {
                    return a[sortColumn] < b[sortColumn] ? 1 : -1;
                  }
                };
                const parseData = sortDirection === 'NONE' ? group[key] : [...group[key]].sort(comparer);
                that.setState({
                  group: {
                    ...that.state.group,
                    pipe: parseData,
                  },
                });
              }

              }
            />
            <h2 style={{
              float: 'right',
              overflow: 'hidden',
              marginTop: '5px',
              marginBottom: '0',
              marginRight: '5px',
            }}>选择管道总长度: {totalLength.toFixed(2)} 米</h2>
          </TabPane>,
        );
      }

    }
    return result;
  };

  render() {
    const { dispatch } = this.props;
    return <div>
      <Tabs type="card">
        {
          this.renderTabPane(this.state.group)
        }
      </Tabs>
    </div>;
  }
}

export default BasicList;
